<!-- AlarmRulesDialog.vue -->
<template>
    <el-dialog draggable v-model="dialogVisible" title="报警规则设置" width="1000px" :close-on-click-modal="false"
        v-loading="loading" element-loading-text="加载中..." fullscreen-loading>
        <div class="rules-container">
            <el-form label-position="top">
                <!-- 搜索和筛选区域 -->
                <div class="filter-area">
                    <el-input v-model="searchKeyword" placeholder="搜索规则..." prefix-icon="Search" clearable
                        class="search-input" />
                    <el-select v-model="categoryFilter" placeholder="类别筛选" clearable>
                        <el-option label="全部类别" value="" />
                        <el-option v-for="category in categoryOptions" :key="category" :label="category"
                            :value="category" />
                    </el-select>
                    <div v-permission="'set_exception'" class="bulk-actions">
                        <el-button size="small" type="primary" @click="selectAllRules"
                            :disabled="loading || pendingChanges.length > 0">全选</el-button>
                        <el-button size="small" @click="unselectAllRules"
                            :disabled="loading || pendingChanges.length > 0">全不选</el-button>
                        <el-button size="small" type="success" @click="resetToDefaultSeverity"
                            :disabled="loading || pendingChanges.length > 0">重置为默认等级</el-button>
                    </div>
                </div>

                <!-- 规则列表 -->
                <el-table :data="filteredRules" style="width: 100%" max-height="400px" border stripe>
                    <el-table-column prop="subCategory" label="规则名称">
                        <template #default="scope">
                            <div>
                                <span class="rule-name">{{ scope.row.subCategory }}</span>
                                <el-tag size="small" class="ml-2" type="success">{{ scope.row.category }}</el-tag>
                                <el-tag size="small" class="ml-2" type="info">{{ scope.row.name }}</el-tag>
                                <!-- 未保存变更指示器 -->
                                <el-tag
                                    v-if="pendingChanges.some(change => change.ruleId === scope.row.id) || notifyPendingChanges.some(change => change.eventTypeId === scope.row.id)"
                                    size="small" class="ml-2" type="warning" effect="plain">
                                    未保存
                                </el-tag>
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column width="120" align="center" label="严重程度">
                        <template #default="scope">
                            <el-select :disabled="!permissionStore.hasPermission('set_exception') || loading"
                                v-model="scope.row.severity" size="small" class="severity-select"
                                @change="(val) => handleSeverityChange(scope.row, val)">
                                <el-option :value="1" label="严重">
                                    <div class="severity-option">
                                        <el-tag type="danger" effect="dark" size="small">严重</el-tag>
                                    </div>
                                </el-option>
                                <el-option :value="2" label="警告">
                                    <div class="severity-option">
                                        <el-tag type="warning" effect="dark" size="small">警告</el-tag>
                                    </div>
                                </el-option>
                                <el-option :value="3" label="提示">
                                    <div class="severity-option">
                                        <el-tag type="info" effect="dark" size="small">提示</el-tag>
                                    </div>
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>

                    <el-table-column v-if="true" align="center" label="单位推送设置" width="120">
                        <template #default="scope">
                            <el-switch :disabled="!permissionStore.hasPermission('set_exception') || loading"
                                v-model="scope.row.isPushEnabled" @change="(val) => handlePushChange(scope.row, val)" />
                        </template>
                    </el-table-column>

                    <el-table-column v-permission="'push_exception_email'" align="center" label="推送至我的邮箱" width="150">
                        <template #header>
                            <div class="column-with-icon">
                                <span>推送至我的邮箱</span>
                                <el-tooltip content="请确保已在个人信息中填写正确的邮箱地址，否则将无法接收推送通知" placement="top">
                                    <el-icon>
                                        <QuestionFilled />
                                    </el-icon>
                                </el-tooltip>
                            </div>
                        </template>
                        <template #default="scope">
                            <el-switch v-model="scope.row.isEmailEnabled"
                                @change="(val) => handleEmailChange(scope.row, val)"
                                :disabled="!scope.row.isPushEnabled" />
                        </template>
                    </el-table-column>

                    <!-- 修改: 微信推送设置增加问号图标 -->
                    <el-table-column v-permission="'push_exception_email'" align="center" label="推送至我的微信" width="150">
                        <template #header>
                            <div class="column-with-icon">
                                <span>推送至我的微信</span>
                                <el-tooltip content="请确保已绑定微信小程序，否则将无法接收推送通知" placement="top">
                                    <el-icon>
                                        <QuestionFilled />
                                    </el-icon>
                                </el-tooltip>
                            </div>
                        </template>
                        <template #default="scope">
                            <el-switch v-model="scope.row.isWechatEnabled"
                                @change="(val) => handleWechatChange(scope.row, val)"
                                :disabled="!scope.row.isPushEnabled" />
                        </template>
                    </el-table-column>

                    <el-table-column v-permission="'set_exception'" align="center" label="操作" width="110">
                        <template #default="scope">
                            <el-button size="small" link @click="resetRuleToDefault(scope.row)"
                                :disabled="pendingChanges.length > 0">
                                重置
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 未保存变更提示 -->
                <div v-if="pendingChanges.length > 0 || notifyPendingChanges.length > 0" class="pending-changes-alert">
                    <el-alert title="有未保存的更改" type="warning" show-icon :closable="false">
                        <div class="pending-changes-count">
                            共有 {{ pendingChanges.length + notifyPendingChanges.length }} 项变更未保存
                        </div>
                    </el-alert>
                </div>
            </el-form>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleCancel" :disabled="loading">取消</el-button>
                <el-button type="primary" @click="saveRules" :loading="loading"
                    :disabled="pendingChanges.length === 0 && notifyPendingChanges.length === 0">
                    保存设置<span v-if="pendingChanges.length > 0 || notifyPendingChanges.length > 0">
                        ({{ pendingChanges.length + notifyPendingChanges.length }})</span>
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, computed } from 'vue';
import { usePermissionStore } from '@/stores/permission';
import { events } from '@/constants';
import {
    getEventRules,
    addEventRule,
    deleteEventRule,
    updateEventRule,
    getNotifySettings,
    addNotifySetting,
    updateNotifySetting,
    deleteNotifySetting
} from '@/api/event';
import { useCompanyStore } from '@/stores/company';
import { useUserStore } from '@/stores/userinfo'; // 导入用户store
import { ElMessage, ElMessageBox } from 'element-plus';
import { handleError } from '@/utils/handleError';
const permissionStore = usePermissionStore();

// 获取当前公司ID
const companyStore = useCompanyStore();
// 获取用户信息
const userStore = useUserStore();
// 对话框可见状态
const dialogVisible = ref(false);
// 搜索关键字
const searchKeyword = ref('');
// 类别筛选
const categoryFilter = ref('');
// 加载状态
const loading = ref(false);
// 已配置规则列表(从API获取)
const configuredRules = ref([]);
// 已配置的通知设置列表
const notifySettings = ref([]);
// 处理过的规则列表
const rulesList = ref([]);
// 原始规则列表（用于恢复）
const originalRulesList = ref([]);
// 待保存的变更
const pendingChanges = ref([]);
// 待保存的通知设置变更
const notifyPendingChanges = ref([]);

// 获取所有可能的类别
const categoryOptions = computed(() => {
    const categories = new Set();
    events.forEach(event => {
        if (event.category) {
            categories.add(event.category);
        }
    });
    return Array.from(categories);
});

// 获取严重等级的文字标签
function getSeverityLabel(severity) {
    switch (severity) {
        case 1:
            return '严重';
        case 2:
            return '警告';
        case 3:
            return '提示';
        default:
            return '未知';
    }
}

// 获取严重等级的标签类型
function getSeverityTagType(severity) {
    switch (severity) {
        case 1:
            return 'danger';
        case 2:
            return 'warning';
        case 3:
            return 'info';
        default:
            return 'info';
    }
}

// 根据搜索和筛选条件过滤规则
const filteredRules = computed(() => {
    return rulesList.value.filter(rule => {
        const matchesKeyword = !searchKeyword.value ||
            (rule.subCategory && rule.subCategory.toLowerCase().includes(searchKeyword.value.toLowerCase())) ||
            (rule.category && rule.category.toLowerCase().includes(searchKeyword.value.toLowerCase())) ||
            (rule.name && rule.name.toLowerCase().includes(searchKeyword.value.toLowerCase()));

        const matchesCategory = !categoryFilter.value || rule.category === categoryFilter.value;

        return matchesKeyword && matchesCategory;
    });
});

// 获取已配置的规则
async function fetchConfiguredRules() {
    loading.value = true;
    try {
        const res = await getEventRules({ id: companyStore.currentCompany.id });
        if (res.data && Array.isArray(res.data)) {
            configuredRules.value = res.data;
        }
    } catch (error) {
        handleError(error, '获取报警规则失败');
    } finally {
        loading.value = false;
    }
}

// 获取通知设置
async function fetchNotifySettings() {
    loading.value = true;
    try {
        const res = await getNotifySettings({ user_id: userStore.userinfo.id });
        if (res.data && Array.isArray(res.data)) {
            notifySettings.value = res.data;
        }
    } catch (error) {
        handleError(error, '获取通知设置失败');
    } finally {
        loading.value = false;
    }
}

// 初始化规则列表
function initRulesList() {
    // 过滤掉空规则（id为0的规则）
    rulesList.value = events.filter(event => event.id !== 0).map(event => {
        // 查找是否存在当前规则的配置
        const existingRule = configuredRules.value.find(rule => rule.event_id === event.id);
        // 查找是否存在当前规则的通知设置
        const notifySetting = notifySettings.value.find(setting => setting.event_type_id === event.id);

        // 为每个规则添加设置
        return {
            ...event,
            // 如果存在配置，使用配置的严重程度，否则使用默认值
            severity: existingRule ? existingRule.agent_level : event.defaultSeverity,
            // 如果存在配置，则表示已启用推送
            isPushEnabled: !!existingRule,
            // 如果存在配置，保存配置ID用于后续更新
            configId: existingRule ? existingRule.id : null,

            // 原始严重程度
            originalSeverity: existingRule ? existingRule.agent_level : event.defaultSeverity,
            // 原始推送状态
            originalIsPushEnabled: !!existingRule,
            // 邮件通知状态
            isEmailEnabled: notifySetting ? notifySetting.is_email_enabled : false,
            // 微信通知状态
            isWechatEnabled: notifySetting ? notifySetting.is_wechat_enabled : false,
            // 原始邮件通知状态
            originalIsEmailEnabled: notifySetting ? notifySetting.is_email_enabled : false,
            // 原始微信通知状态
            originalIsWechatEnabled: notifySetting ? notifySetting.is_wechat_enabled : false,
            // 通知设置是否存在
            hasNotifySetting: !!notifySetting
        };
    });

    // 深拷贝原始规则列表，用于恢复
    originalRulesList.value = JSON.parse(JSON.stringify(rulesList.value));

    // 清空待保存的变更
    pendingChanges.value = [];
    notifyPendingChanges.value = [];
}

// 处理推送状态变化 - 改进版
function handlePushChange(rule, isEnabled) {
    // 创建一个函数来检查当前值是否与原始值相同
    const isEqualToOriginal = () => {
        return rule.originalIsPushEnabled === isEnabled &&
            (!isEnabled || (isEnabled && rule.severity === rule.originalSeverity));
    };

    // 检查是否真的有变化
    if (isEqualToOriginal()) {
        // 如果是恢复原始状态，从待保存变更中移除
        pendingChanges.value = pendingChanges.value.filter(change =>
            !(change.ruleId === rule.id && (change.type === 'push' || change.type === 'severity')));
        return;
    }

    // 查找是否已存在对应规则的推送变更
    const existingChangeIndex = pendingChanges.value.findIndex(
        change => change.ruleId === rule.id && change.type === 'push'
    );

    if (existingChangeIndex !== -1) {
        // 如果已存在变更，更新它
        pendingChanges.value[existingChangeIndex] = {
            type: 'push',
            ruleId: rule.id,
            action: isEnabled ? 'add' : 'delete',
            data: {
                id: rule.configId,
                name: rule.subCategory || rule.name,
                company_id: companyStore.currentCompany.id,
                event_id: rule.id,
                agent_level: rule.severity
            }
        };
    } else {
        // 如果不存在，添加新的变更
        pendingChanges.value.push({
            type: 'push',
            ruleId: rule.id,
            action: isEnabled ? 'add' : 'delete',
            data: {
                id: rule.configId,
                name: rule.subCategory || rule.name,
                company_id: companyStore.currentCompany.id,
                event_id: rule.id,
                agent_level: rule.severity
            }
        });
    }

    // 如果关闭推送，也要更新通知设置
    if (!isEnabled) {
        // 如果存在通知设置，添加删除变更
        if (rule.hasNotifySetting || rule.isEmailEnabled || rule.isWechatEnabled) {
            // 将邮件和微信都设置为禁用状态
            rule.isEmailEnabled = false;
            rule.isWechatEnabled = false;

            // 添加删除通知设置的变更
            const existingNotifyIndex = notifyPendingChanges.value.findIndex(
                change => change.eventTypeId === rule.id
            );

            if (existingNotifyIndex !== -1) {
                notifyPendingChanges.value[existingNotifyIndex] = {
                    type: 'notify',
                    eventTypeId: rule.id,
                    action: 'delete',
                    data: {
                        user_id: userStore.userinfo.id,
                        event_type_id: rule.id
                    }
                };
            } else {
                notifyPendingChanges.value.push({
                    type: 'notify',
                    eventTypeId: rule.id,
                    action: 'delete',
                    data: {
                        user_id: userStore.userinfo.id,
                        event_type_id: rule.id
                    }
                });
            }
        }
    }
}

// 处理严重程度变化 - 改进版
function handleSeverityChange(rule, newSeverity) {
    // 如果规则未启用推送，则此变更无需保存
    if (!rule.isPushEnabled) {
        return;
    }

    // 检查是否有变化
    if (rule.originalSeverity === newSeverity) {
        // 如果是恢复原始状态，从待保存变更中移除
        pendingChanges.value = pendingChanges.value.filter(change =>
            !(change.ruleId === rule.id && change.type === 'severity'));
        return;
    }

    // 只有当规则已启用推送时才需要更新严重程度
    if (rule.configId) {
        // 查找是否已存在对应规则的严重程度变更
        const existingChangeIndex = pendingChanges.value.findIndex(
            change => change.ruleId === rule.id && change.type === 'severity'
        );

        if (existingChangeIndex !== -1) {
            // 如果已存在变更，更新它
            pendingChanges.value[existingChangeIndex] = {
                type: 'severity',
                ruleId: rule.id,
                action: 'update',
                data: {
                    id: rule.configId,
                    company_id: companyStore.currentCompany.id,
                    event_id: rule.id,
                    agent_level: newSeverity
                }
            };
        } else {
            // 如果不存在，添加新的变更
            pendingChanges.value.push({
                type: 'severity',
                ruleId: rule.id,
                action: 'update',
                data: {
                    id: rule.configId,
                    company_id: companyStore.currentCompany.id,
                    event_id: rule.id,
                    agent_level: newSeverity
                }
            });
        }
    } else {
        // 如果规则已启用推送但没有configId，说明是新增的规则，需要添加push变更
        handlePushChange(rule, true);
    }
}

// 处理邮件通知状态变化 - 改进版
function handleEmailChange(rule, isEnabled) {
    // 如果规则未启用推送，则不处理
    if (!rule.isPushEnabled) return;

    // 定义是否与原始状态相同的函数
    const isEqualToOriginal = () => {
        // 如果原来没有通知设置，则原始值为false
        const originalValue = rule.hasNotifySetting ? rule.originalIsEmailEnabled : false;
        return originalValue === isEnabled;
    };

    // 检查是否有变化
    if (isEqualToOriginal()) {
        // 如果是恢复原始状态，从待保存变更中移除
        notifyPendingChanges.value = notifyPendingChanges.value.filter(change =>
            !(change.eventTypeId === rule.id &&
                change.type === 'notify' &&
                (change.field === 'email' || change.field === 'both')));

        // 如果两个设置都恢复了原始状态，可能需要移除整个通知变更
        const wechatNotChanged = rule.isWechatEnabled === (rule.hasNotifySetting ? rule.originalIsWechatEnabled : false);
        if (wechatNotChanged) {
            notifyPendingChanges.value = notifyPendingChanges.value.filter(change =>
                !(change.eventTypeId === rule.id && change.type === 'notify'));
        }

        return;
    }

    // 查找是否已存在对应规则的通知设置变更
    const existingChangeIndex = notifyPendingChanges.value.findIndex(
        change => change.eventTypeId === rule.id && change.type === 'notify'
    );

    if (existingChangeIndex !== -1) {
        // 如果已存在变更，更新它
        const existingChange = notifyPendingChanges.value[existingChangeIndex];

        // 更新已有的变更
        notifyPendingChanges.value[existingChangeIndex] = {
            ...existingChange,
            field: 'both', // 标记为同时变更邮件和微信
            action: rule.hasNotifySetting ? 'update' : 'add',
            data: {
                ...existingChange.data,
                user_id: userStore.userinfo.id,
                event_type_id: rule.id,
                is_email_enabled: isEnabled,
                is_wechat_enabled: rule.isWechatEnabled
            }
        };
    } else {
        // 如果不存在变更
        notifyPendingChanges.value.push({
            type: 'notify',
            eventTypeId: rule.id,
            action: rule.hasNotifySetting ? 'update' : 'add',
            field: 'both',
            data: {
                user_id: userStore.userinfo.id,
                event_type_id: rule.id,
                is_email_enabled: isEnabled,
                is_wechat_enabled: rule.isWechatEnabled
            }
        });
    }
}

// 处理微信通知状态变化 - 改进版
function handleWechatChange(rule, isEnabled) {
    // 如果规则未启用推送，则不处理
    if (!rule.isPushEnabled) return;

    // 定义是否与原始状态相同的函数
    const isEqualToOriginal = () => {
        // 如果原来没有通知设置，则原始值为false
        const originalValue = rule.hasNotifySetting ? rule.originalIsWechatEnabled : false;
        return originalValue === isEnabled;
    };

    // 检查是否有变化
    if (isEqualToOriginal()) {
        // 如果是恢复原始状态，从待保存变更中移除
        notifyPendingChanges.value = notifyPendingChanges.value.filter(change =>
            !(change.eventTypeId === rule.id &&
                change.type === 'notify' &&
                (change.field === 'wechat' || change.field === 'both')));

        // 如果两个设置都恢复了原始状态，可能需要移除整个通知变更
        const emailNotChanged = rule.isEmailEnabled === (rule.hasNotifySetting ? rule.originalIsEmailEnabled : false);
        if (emailNotChanged) {
            notifyPendingChanges.value = notifyPendingChanges.value.filter(change =>
                !(change.eventTypeId === rule.id && change.type === 'notify'));
        }

        return;
    }

    // 查找是否已存在对应规则的通知设置变更
    const existingChangeIndex = notifyPendingChanges.value.findIndex(
        change => change.eventTypeId === rule.id && change.type === 'notify'
    );

    if (existingChangeIndex !== -1) {
        // 如果已存在变更，更新它
        const existingChange = notifyPendingChanges.value[existingChangeIndex];

        // 更新已有的变更
        notifyPendingChanges.value[existingChangeIndex] = {
            ...existingChange,
            field: 'both', // 标记为同时变更邮件和微信
            action: rule.hasNotifySetting ? 'update' : 'add',
            data: {
                ...existingChange.data,
                user_id: userStore.userinfo.id,
                event_type_id: rule.id,
                is_email_enabled: rule.isEmailEnabled,
                is_wechat_enabled: isEnabled
            }
        };
    } else {
        // 如果不存在变更
        notifyPendingChanges.value.push({
            type: 'notify',
            eventTypeId: rule.id,
            action: rule.hasNotifySetting ? 'update' : 'add',
            field: 'both',
            data: {
                user_id: userStore.userinfo.id,
                event_type_id: rule.id,
                is_email_enabled: rule.isEmailEnabled,
                is_wechat_enabled: isEnabled
            }
        });
    }
}

// 将单个规则重置为默认等级
function resetRuleToDefault(rule) {
    if (rule.severity === rule.defaultSeverity) {
        ElMessage.info('当前规则已是默认等级');
        return;
    }

    rule.severity = rule.defaultSeverity;
    handleSeverityChange(rule, rule.defaultSeverity);
    ElMessage.success(`已将 "${rule.subCategory}" 重置为默认等级`);
}

// 将所有规则重置为默认等级
function resetToDefaultSeverity() {
    if (loading.value || pendingChanges.value.length > 0) return;

    // 计数器，记录实际变化的规则数量
    let changedCount = 0;

    // 处理所有可见的规则
    for (const rule of filteredRules.value) {
        if (rule.severity !== rule.defaultSeverity) {
            rule.severity = rule.defaultSeverity;
            handleSeverityChange(rule, rule.defaultSeverity);
            changedCount++;
        }
    }

    if (changedCount > 0) {
        ElMessage.success(`已将 ${changedCount} 条规则重置为默认等级，请点击保存按钮提交更改`);
    } else {
        ElMessage.info('所有规则已是默认等级');
    }
}

// 保存规则设置
async function saveRules() {
    if (pendingChanges.value.length === 0 && notifyPendingChanges.value.length === 0) {
        ElMessage.info('没有需要保存的变更');
        return;
    }

    loading.value = true;
    const errors = [];

    try {
        // 处理所有待保存的规则变更
        for (const change of pendingChanges.value) {
            try {
                if (change.type === 'push') {
                    if (change.action === 'add') {
                        // 添加规则
                        const response = await addEventRule(change.data);
                        if (response && response.data) {
                            // 更新规则ID
                            const rule = rulesList.value.find(r => r.id === change.ruleId);
                            if (rule) {
                                rule.configId = response.data.id;
                                rule.originalIsPushEnabled = true;
                            }
                        }
                    } else if (change.action === 'delete') {
                        // 删除规则
                        await deleteEventRule({ id: String(change.data.id) });
                        // 更新规则状态
                        const rule = rulesList.value.find(r => r.id === change.ruleId);
                        if (rule) {
                            rule.configId = null;
                            rule.originalIsPushEnabled = false;
                        }
                    }
                } else if (change.type === 'severity') {
                    // 更新规则
                    await updateEventRule(change.data);
                    // 更新规则状态
                    const rule = rulesList.value.find(r => r.id === change.ruleId);
                    if (rule) {
                        rule.originalSeverity = change.data.agent_level;
                    }
                }
            } catch (error) {
                errors.push(error);
                console.error('Error saving rule change:', change, error);
            }
        }

        // 处理所有待保存的通知设置变更
        for (const change of notifyPendingChanges.value) {
            try {
                if (change.action === 'add') {
                    // 添加通知设置
                    await addNotifySetting(change.data);

                    // 更新规则状态
                    const rule = rulesList.value.find(r => r.id === change.eventTypeId);
                    if (rule) {
                        rule.hasNotifySetting = true;
                        rule.originalIsEmailEnabled = change.data.is_email_enabled;
                        rule.originalIsWechatEnabled = change.data.is_wechat_enabled;
                    }
                } else if (change.action === 'update') {
                    // 更新通知设置
                    await updateNotifySetting(change.data);

                    // 更新规则状态
                    const rule = rulesList.value.find(r => r.id === change.eventTypeId);
                    if (rule) {
                        if (change.data.is_email_enabled !== undefined) {
                            rule.originalIsEmailEnabled = change.data.is_email_enabled;
                        }
                        if (change.data.is_wechat_enabled !== undefined) {
                            rule.originalIsWechatEnabled = change.data.is_wechat_enabled;
                        }
                    }
                } else if (change.action === 'delete') {
                    // 删除通知设置
                    await deleteNotifySetting(change.data);

                    // 更新规则状态
                    const rule = rulesList.value.find(r => r.id === change.eventTypeId);
                    if (rule) {
                        rule.hasNotifySetting = false;
                        rule.originalIsEmailEnabled = false;
                        rule.originalIsWechatEnabled = false;
                    }
                }
            } catch (error) {
                errors.push(error);
                console.error('Error saving notify change:', change, error);
            }
        }

        const totalChanges = pendingChanges.value.length + notifyPendingChanges.value.length;
        if (errors.length > 0) {
            ElMessage.warning(`部分设置保存失败，成功保存 ${totalChanges - errors.length}/${totalChanges} 项`);
        } else {
            ElMessage.success('规则设置已保存');
        }

        // 重新获取规则以确保数据同步
        await fetchConfiguredRules();
        await fetchNotifySettings();
        initRulesList();

        // 关闭对话框
        dialogVisible.value = false;
    } catch (error) {
        handleError(error, '保存规则设置失败');
    } finally {
        loading.value = false;
    }
}

// 取消更改并关闭对话框
function handleCancel() {
    if (pendingChanges.value.length > 0 || notifyPendingChanges.value.length > 0) {
        ElMessageBox.confirm(
            '有未保存的更改，确定要取消吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            // 恢复原始状态并关闭对话框
            rulesList.value = JSON.parse(JSON.stringify(originalRulesList.value));
            pendingChanges.value = [];
            notifyPendingChanges.value = [];
            dialogVisible.value = false;
        }).catch(() => {
            // 用户取消关闭操作，不做任何处理
        });
    } else {
        dialogVisible.value = false;
    }
}

// 全选所有规则
function selectAllRules() {
    if (loading.value || pendingChanges.value.length > 0) return;

    // 计数器，记录实际变化的规则数量
    let changedCount = 0;

    // 处理所有可见的规则
    for (const rule of filteredRules.value) {
        if (!rule.isPushEnabled) {
            rule.isPushEnabled = true;
            handlePushChange(rule, true);
            changedCount++;
        }
    }

    if (changedCount > 0) {
        ElMessage.success(`已选中 ${changedCount} 条规则，请点击保存按钮提交更改`);
    } else {
        ElMessage.info('所有规则已全部选中');
    }
}

// 取消全选所有规则
function unselectAllRules() {
    if (loading.value || pendingChanges.value.length > 0) return;

    // 计数器，记录实际变化的规则数量
    let changedCount = 0;

    // 处理所有可见的规则
    for (const rule of filteredRules.value) {
        if (rule.isPushEnabled) {
            rule.isPushEnabled = false;
            handlePushChange(rule, false);
            changedCount++;
        }
    }

    if (changedCount > 0) {
        ElMessage.success(`已取消选中 ${changedCount} 条规则，请点击保存按钮提交更改`);
    } else {
        ElMessage.info('所有规则已全部取消选中');
    }
}

// 打开对话框的方法（供父组件调用）
async function openDialog() {
    // 重置搜索和筛选条件
    searchKeyword.value = '';
    categoryFilter.value = '';
    // 获取已配置的规则
    await fetchConfiguredRules();
    // 获取通知设置
    await fetchNotifySettings();
    // 初始化规则列表
    initRulesList();
    // 显示对话框
    dialogVisible.value = true;
}

// 向父组件暴露方法
defineExpose({
    openDialog
});
</script>

<style scoped>
.rules-container {
    max-height: 600px;
    overflow-y: auto;
}

.column-with-icon {
    display: flex;
    align-items: center;
    gap: 4px;
}

.filter-area {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
    align-items: center;
}

.bulk-actions {
    display: flex;
    gap: 8px;
    margin-left: auto;
}

.search-input {
    width: 240px;
}

.severity-select {
    width: 100%;
}

.rule-name {
    font-weight: bold;
}

.ml-2 {
    margin-left: 8px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.pending-changes-alert {
    margin-top: 16px;
}

.pending-changes-count {
    margin-top: 4px;
    font-size: 12px;
    color: #e6a23c;
}
</style>